// data = {
// 	title: '名称',
//  options: (option) => { return option }, // 自定义options
// 	color: [{color1: '主色', color2: '折线图渐变色'}], // 多个 与dataKey对应
// 	dataKey: [{ name, value }] // 多个
// }
import * as echarts from 'echarts'
function toThousands(num) {
  return num?.toString()?.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') || 0;
}
export const initECharts = (data, echartType) => {
	const { myChart } = data
	const maxLabelCount = Math.floor(myChart?._api?.getWidth() / 5 / 12)
	// const map = {
	// 	asset: '资产',
	// 	vul: '漏洞',
	// 	security_event: '安全事件'
	// }
	// const colorMap = {
	// 	asset: { 资产总数: '#0B6FD6',
	// 		已确认资产数: '#11AB4E',
	// 		待确认资产数: '#FE8A1F'
	// 	},
	// 	vul: '#FF0000',
	// 	security_event: '#FE8A1F'
	// }
	// const color2Map = {
	// 	asset: { 资产总数: 'rgba(26, 168, 237, 0)',
	// 		已确认资产数: 'rgba(22, 173, 82, 0)',
	// 		待确认资产数: 'rgba(255, 255, 255, 0)'
	// 	},
	// 	vul: 'rgba(240, 64, 56, 0)',
	// 	security_event: 'rgba(255, 255, 255, 0)'
	// }
	const labelLevelMap = {
		critical: '严重',
		high: '高危',
		medium: '中危',
		low: '低危',
		risk_link: '风险外链',
		black_links: '暗链',
		keyword: '敏感词',
		cryptojacking: '挖矿',
		malscan: '挂马',
		privacy_disclosure: '隐私信息',
		broken_link: '坏链'
	}
	// const levelColor = {
	// 	critical: '#BB0707',
	// 	high: '#FF0000',
	// 	medium: '#F67E23',
	// 	low: '#FED831',
	// 	risk_link_high_level: '#FF0000',
	// 	risk_link_medium_level: '#F67E23',
	// 	risk_link_low_level: '#FED831',
	// 	black_links: '#FF0000',
	// 	keyword: '#FED831',
	// 	cryptojacking: '#FF0000',
	// 	malscan: '#FF0000',
	// 	privacy_disclosure: '#FED831',
	// 	broken_link: '#FED831'
	// }
	const pieDataTotal = data?.dataKey?.reduce((t, i) => {
		t += i.value
		return t
	}, 0)
	const option = {
		line: {
			grid: {
				left: 0,
				bottom: 0,
				right: 0,
				top: 10
			},
			tooltip: {
				show: true,
				position: function (pos, params, dom, rect, size) {
					var obj = {};
					obj[['top', 'bottom'][+(pos[1] < size.viewSize[1] / 2)]] = -20;
					obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
					return obj;
				},
				trigger: 'axis',
				backgroundColor: 'rgba(255, 255, 255, .7)',
				axisPointer: {
					lineStyle: {
						color: '#E6EAEF'
					}
				},
				padding: [5, 10],
				formatter: function ([value]) {
					let html = `<div style='font-size: 12px;color: #686C78'>
						<div>${value?.axisValue}</div>
						${data?.dataKey?.map((item, k) => {
							return `<div style='display: flex;align-items: center;min-width: 100px;justify-content: space-between;'>
								<div style='display: flex;align-items: center;margin-right: 40px;'>
									<span style='width: 6px;height: 6px;border-radius: 50%;margin-right: 5px;background: ${data?.color[k].color1};'></span>
									<span>${item.name}</span>
								</div>
								<div stype='color: #1E1F23;font-weight: bold;'>${toThousands(item.value?.[value?.dataIndex])}</div>
							</div>`
						}).join('')}
					</div>`
					return html
				}
			},
			xAxis: {
				show: false,
				type: 'category',
				boundaryGap: false,
				minInterval: 1,
				data: Object.keys(data) || []
			},
			yAxis: {
				type: 'value',
				minInterval: 1,
				show: false
			},
			color: data?.color?.map(i => { return i?.color1 }),
			series: data?.dataKey.reduce((t, item, key) => {
				if (item.show) {
					t.push({
						name: item.name,
						data: item.value,
						type: 'line',
						title: item.name,
						symbolSize: item.symbolSize || 0,
						show: item.show,
						showAllSymbol: item.showAllSymbol,
						color: data.color[key].color1,
						...(data.color[key].color2 ? { areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{
									offset: 1,
									color: data.color[key].color2
								},
								{
									offset: 0,
									color: data.color[key].color1
								}
							])
						}} : {})
					})
				}
				return t
			}, [])
		},
		bar: {
			title: {
				text: data?.title,
				textStyle: {
					...(data?.textStyle || {}),
					color: '#686C78',
					fontWeight: 'normal',
					fontSize: 14
				}
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: { type: 'none', lineStyle: {
					color: '#E6EAEF'
				}},
				backgroundColor: 'rgba(255, 255, 255, 0)',
				padding: 0,
				formatter: function (value) {
					let html = `<div style='font-size: 12px;color: #686C78;padding: 5px 10px; background-color: rgba(255, 255, 255, 0.9)' class='wContent'>
						<div style='max-width:300px;white-space: pre-wrap;'>${value[0]?.axisValueLabel}</div>`
					const itemHtml = value.map(item => {
						return item?.value === 0 ? '' : `<div style='display: flex;align-items: center;min-width: 100px;justify-content: space-between;'>
							<div style='display: flex;align-items: center;margin-right: 10px;'>
								<span style='width: 6px;height: 6px;border-radius: 50%;margin-right: 5px;background: ${item?.color};'></span>
								<span>${item?.seriesName}</span>
							</div>
							<div stype='color: #1E1F23;font-weight: bold;'>${toThousands(item?.data?.realValue || item?.value)}</div>
						</div>`
					}).join('')
					html += itemHtml
					html += `</div>`
					if (!itemHtml) {
						return ''
					}
					return html
				}
			},
			legend: {
				right: 0,
				itemWidth: 11,
				itemHeight: 8,
				textStyle: {
					color: '#686C78',
					fontSize: 12
				}
			},
			color: data?.color?.map(i => { return i?.color1 }),
			grid: {
				left: '1%',
				right: '0',
				bottom: 0,
				top: '24%',
				containLabel: true
			},
			xAxis: {
				show: false,
				type: 'value',
				data: [],
				minInterval: 1,
				max: 'dataMax',
				triggerEvent: true,
				axisLine: {
					lineStyle: {
						color: '#F7F9FC'
					}
				},
				axisLabel: {
					fontSize: 12,
					color: '#686C78',
					interval: 0,
					formatter: function (value) {
						// x轴左右留存间距
						return value?.length > (maxLabelCount - 2) ? value.substring(0, (maxLabelCount - 2)) + '...' : value
					},
				},
				axisTick: {
					show: false
				},
			},
			yAxis: {
				type: 'category',
				minInterval: 1,
				axisLine: {
					lineStyle: {
						color: '#F7F9FC'
					}
				},
				triggerEvent: true,
				splitLine: {
					lineStyle: {
						color: '#F7F9FC'
					}
				},
				axisLabel: {
					textStyle: {
						fontSize: 12,
						color: '#686C78'
					},
					formatter: function (value) {
						return value?.length > maxLabelCount ? value.substring(0, maxLabelCount) + '...' : value
					},
				},
				axisTick: {
					show: false
				},
			},
			series: data?.dataKey?.map((i, k) => {
				const { name, value: data, stack, label } = i
				return {
					name,
					type: 'bar',
					data,
					stack,
					label: {
						show: label,
						position: 'top',
						color: '#999EA8',
						formatter: ({ value }) => {
							if (value) {
								return value
							} else {
								return ''
							}
						}
					},
					barWidth: 6,
					barGap: '60%'
				}
			})
		},
		totalBar: {
			tooltip: {
				trigger: 'axis',
				axisPointer: { type: 'none', lineStyle: {
					color: '#E6EAEF'
				}},
				position: function (pos, params, dom, rect, size) {
					var obj = {};
					obj[['top', 'bottom'][+(pos[1] < size.viewSize[1] / 2)]] = -20;
					obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
					return obj;
				},
				backgroundColor: 'rgba(255, 255, 255, 0)',
				padding: 0,
				formatter: function (value) {
					let html = `<div style='max-width: 300px; font-size: 12px;color: #686C78;padding: 5px 10px; background-color: rgba(255, 255, 255, 0.9)' class='wContent'>
						<div>${data?.dataKey[0]?.target}</div>
						<div style='width: 100%;white-space: pre-wrap;'>${data?.dataKey[0]?.target_name}</div>
					`
					html += value?.reduce((t, item) => {
						if (labelLevelMap[item.seriesName]) {
							t += `<div style='display: flex;align-items: center;min-width: 100px;justify-content: space-between;'>
								<div style='display: flex;align-items: center;'>
									<span style='width: 6px;height: 6px;border-radius: 50%;margin-right: 5px;background: ${item.color};'></span>
									<span>${labelLevelMap[item.seriesName]}</span>
								</div>
								<div stype='color: #1E1F23;font-weight: bold;'>${toThousands(item.data)}</div>
							</div>`
						}
						return t
					}, '')
					html += `</div>`
					if (data?.itemTotal === 0) {
						return ''
					}
					return html
				}
			},
			title: { show: false },
			legend: { show: false },
			grid: {
				left: 0,
				right: 0,
				top: 0,
				bottom: '-38px',
				containLabel: false
			},
			xAxis: {
				show: false,
				type: 'value',
				max: 'dataMax',
				minInterval: 1,
			},
			yAxis: {
				type: 'category',
				minInterval: 1,
				show: false,
				data: ['']
			},
			series: data?.dataKey?.map((i, k) => {
				return {
					name: i.name,
					type: 'bar',
					stack: 'total',
					barWidth: 6,
					itemStyle: {
						color: i.color || data?.color?.[k]?.color1
					},
					emphasis: {
						itemStyle: {
							color: data?.color?.[k]?.color1
						},
					},
					data: [i.value]
				}
			})
		},
		pie: {
			title: {
				text: data?.title,
				top: "middle",
				left: "19%",
				textAlign: "center",
				textStyle: {
					fontSize: 14,
					fontWeight: "normal",
				},
			},
			tooltip: {
				confine: true,
				trigger: "item",
				formatter: ({ data: { name, totalValue }, percent }) => {
					return `${name} : ${totalValue} (${percent}%)`
				},
			},
			legend: {
				orient: "horizontal",
				left: "40%",
				top: "middle",
				align: "left",
				itemGap: 16,
				icon: "circle",
				itemHeight: 9,
				itemWidth: 9,
				data: data?.dataKey?.map((i, k) => {
					const { name, value } = i
					return {
						name,
						value,
						itemStyle: {
							color: data?.color?.[k]?.color1,
						},
					}
				}).filter(i => i),
				textStyle: { padding: [0, 3], width: 40 },
				formatter: (name) => {
					let value = "";
					data?.dataKey.map((e) => {
						e.name === name && (value = e.value);
					});
					return `${name}: ${toThousands(value)}`;
				}
			},
			series: [{
				type: "pie",
				radius: ["60%", "75%"],
				center: ["20%", "50%"],
				label: {
					normal: {
						show: false,
						position: "outside",
					},
					emphasis: {
						show: false,
						textStyle: {
							fontSize: 20,
							fontWeight: "normal",
						},
					},
				},
				labelLine: {
					normal: {
						show: false,
					},
					emphasis: {
						show: false,
					},
				},
				data: data?.dataKey?.map((i, k) => {
					const { name, value } = i
					return {
						name,
						value: (value && value / pieDataTotal * 100 < 1) ? pieDataTotal * 0.01 : value,
						totalValue: value,
						itemStyle: {
							color: data?.color?.[k]?.color1
						},
					}
				}).filter(i => i)
			}],
		}
	}
	const newOptions = data?.options ? data?.options(option[echartType]) : option[echartType]
	return newOptions
};
